#pragma once
#include "yzrutil.h"
#include "DSP.h"
#include "RingBuffer.h"
#include "array/Arrays.h"
#include "BufferDelayer.h"
#include "AllPassFilter.h"
#include <vector>
#include "Oscillator.h"
namespace yzrilyzr_dsp{
	ECLASS(Phaser, public DSP){
	private:
	u_sample depthMul=0;
	std::vector<std::shared_ptr<AllPassFilter>> allPassFilters;
	RingBufferSample buffer; // 用于反馈（如果使用）
	u_sample bufferLength=0;
	u_sample_rate sampleRate=0;
	public:
	DSPPtr osc=nullptr;
	u_time_ms depthMs=1.0; // ms
	u_normal_01 wetRatio=0; // %
	u_normal_11 feedback=0; // %
	uint32_t stages=4; // 全通滤波器的级数

	BufferDelayer::DelayFunction delayFunction=BufferDelayer::linearDelay;

	Phaser();

	Phaser(u_freq rate, u_time_ms depthMs, u_normal_01 wetRatio, u_normal_11 feedback, int stages=4)
		:Phaser(std::make_shared<SineOscillator>(rate),depthMs,wetRatio,feedback,stages){}
	Phaser(DSPPtr osc, u_time_ms depthMs, u_normal_01 wetRatio, u_normal_11 feedback, int stages=4)
		: osc(osc), depthMs(depthMs), wetRatio(wetRatio), feedback(feedback), stages(stages){}

	u_sample procDsp(u_sample in) override{
		if(wetRatio == 0 || depthMs == 0 ) return in;
		// 计算LFO调制量（范围0~1）
		u_sample delayIndex=depthMul * (1 + osc->procDsp(in));
		if(delayIndex <= 0) return in;

		// 处理全通滤波器链
		u_sample signal=in;
		for(auto apf : allPassFilters){
			// 设置每个APF的延迟时间（基于调制量）
			apf->delayTimeMs=delayIndex * 1000.0; // 转换为ms
			apf->init(sampleRate); // 转换为ms
			signal=apf->procDsp(signal);
		}

		// 应用反馈（可选）
		u_sample output=signal;
		if(feedback != 0){
			buffer.write(in + output * feedback);
			output=delayFunction(buffer, bufferLength);
		}

		// 混合干湿信号
		return output * wetRatio + in * (1 - wetRatio);
	}

	void init(u_sample_rate sampleRate) override{
		osc->init(sampleRate);
		this->sampleRate=sampleRate;
		depthMul=depthMs / 1000.0; // 转换为秒

		// 初始化全通滤波器
		allPassFilters.clear();
		for(uint32_t i=0; i < stages; i++){
			std::shared_ptr<AllPassFilter> apf=std::make_shared<AllPassFilter>(depthMs, 0.7f); // 增益通常设为0.7左右
			apf->init(sampleRate);
			allPassFilters.push_back(apf);
		}

		// 初始化反馈缓冲区（如果需要）
		bufferLength=sampleRate * depthMs / 1000.0;
		buffer.ensureCapacity((u_index)sampleRate);
	}

	void resetMemory() override{
		osc->resetMemory();
		for(auto & apf : allPassFilters){
			apf->resetMemory();
		}
		buffer.fill(0);
	}

	std::shared_ptr<DSP> cloneDSP() override{
		return std::make_shared<Phaser>(osc->cloneDSP(), depthMs, wetRatio, feedback, stages);
	}

	void cloneParam(DSP * obj1) override{
		if(auto other=dynamic_cast<Phaser *>(obj1)){
			wetRatio=other->wetRatio;
			osc->cloneParam(other->osc.get());
			depthMs=other->depthMs;
			feedback=other->feedback;
			stages=other->stages;
			delayFunction=other->delayFunction;
		}
	}
	yzrilyzr_lang::String toString()const override;
	};
}